package com.zysoft.function;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.idcard.huashi.R;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wmf
 * 通用方法封装
 */
public class ApiUtil{

    private Dialog loadingDialog;
    public MyDatabaseHelper dbhelp;//数据库初始化;http://ct.baozhizhi.com:8100/

    private static final String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();

//    public String UpdateUrl="";//版本更新接口
    public String Login = "http://ts.ehjedu.cn:8100/authentication/form";//登录接口
    public String ProjectInf = "http://ts.ehjedu.cn:8100/api/open/v1/project/findProjectPageList";//项目信息接口
    public String ExitPerson = "http://ts.ehjedu.cn:8100/api/open/v1/project/findProjectWorkerInfoPage";//根据项目code退场信息接口
    public String DepartTeam = "http://ts.ehjedu.cn:8100/api/open/v1/findOrgnizationTreeByProjectCode";//根据项目code查询班组接口
    public String DictionaryItem = "http://ts.ehjedu.cn:8100/api/open/v1/dictionary/workerFormDictionary";//字典项
    public String ImageUrl = "http://111.47.7.125:8071/document/uploadFilePrintWrite";//图片上传接口
    public String LogUrl = "http://ts.ehjedu.cn:8100/api/open/v1/log/saveLogInfo";//日志上传
    public String SubmitData ="http://ts.ehjedu.cn:8100/api/open/v1/worker/saveWorker";//数据提交接口
    public String ExitUrl = "http://ts.ehjedu.cn:8100/api/open/v1/project/exitWorkerById";//人员退场接口
    public String teamAdd = "http://ts.ehjedu.cn:8100/api/open/v1/project/addMaster";//班组添加
//    public String LogUrl = "http://10.5.77.130:8100/api/open/v1/log/saveLogInfo";//日志上传
//    public String Login = "http://10.5.77.130:8100/authentication/form";//登录接口
//    public String ProjectInf = "http://10.5.77.130:8100/api/open/v1/project/findProjectPageList";//项目信息接口
//    public String ExitPerson = "http://10.5.77.130:8100/api/open/v1/project/findProjectWorkerInfoPage";//根据项目code退场信息接口
//    public String DepartTeam = "http://10.5.77.130:8100/api/open/v1/findOrgnizationTreeByProjectCode";//根据项目code查询班组接口
//    public String DictionaryItem = "http://10.5.77.130:8100/api/open/v1/dictionary/workerFormDictionary";//字典项
//    public String ImageUrl = "http://10.5.54.43:8071/document/uploadFilePrintWrite";//图片上传接口
//    public String SubmitData ="http://10.5.77.130:8100/api/open/v1/worker/saveWorker";//数据提交接口
//    public String ExitUrl = "http://10.5.77.130:8100/api/open/v1/project/exitWorkerById";//人员退场接口
//    public String teamAdd = "http://10.5.77.130:8100/api/open/v1/project/addMaster";//班组添加

//    public String Login = "http://ct.baozhizhi.com:8100/authentication/form";//登录接口
//    public String ProjectInf = "http://ct.baozhizhi.com:8100/api/open/v1/project/findProjectPageList";//项目信息接口
//    public String ExitPerson = "http://ct.baozhizhi.com:8100/api/open/v1/project/findProjectWorkerInfoPage";//根据项目code退场信息接口
//    public String DepartTeam = "http://ct.baozhizhi.com:8100/api/open/v1/findOrgnizationTreeByProjectCode";//根据项目code查询班组接口
//    public String DictionaryItem = "http://ct.baozhizhi.com:8100/api/open/v1/dictionary/workerFormDictionary";//字典项
//    public String ImageUrl = "http://111.47.7.125:8071/document/uploadFilePrintWrite";//图片上传接口
//    public String SubmitData ="http://ct.baozhizhi.com:8100/api/open/v1/worker/saveWorker";//数据提交接口
//    public String ExitUrl = "http://ct.baozhizhi.com:8100/api/open/v1/project/exitWorkerById";//人员退场接口
//    public String teamAdd = "http://ct.baozhizhi.com:8100/api/open/v1/project/addMaster";//班组添加


    //日志打印
    public void Log(String log){
        Log.e("zysoft",log);
    }

    //初始化Loading加载框
    public void init(Context context){
        loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
    }
    //uuid生成
    public String uuid(){
        return UUID.randomUUID().toString().replace("-", "");
    }
    public String transNum(int one,int two) {
        double result = new BigDecimal(one / two).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        String num =  String.valueOf(result*100);
        return num.substring(0,num.indexOf("."));
    }
    public String infouid(Context context){
        String uid = "";
        try {
            PackageManager pm = context.getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo("com.idcard.huashi", PackageManager.GET_META_DATA);
            uid = String.valueOf(ai.uid);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return uid;
    }
    public String dateTime(){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String str = formatter.format(date);
        return  str;
    }
    public boolean copyFile(String oldPath$Name, String newPath$Name) {
        try {
            File oldFile = new File(oldPath$Name);
            if (!oldFile.exists()) {
                Log.e("--Method--", "copyFile:  oldFile not exist.");
                return false;
            } else if (!oldFile.isFile()) {
                Log.e("--Method--", "copyFile:  oldFile not file.");
                return false;
            } else if (!oldFile.canRead()) {
                Log.e("--Method--", "copyFile:  oldFile cannot read.");
                return false;
            }

            FileInputStream fileInputStream = new FileInputStream(oldPath$Name);    //读入原文件
            FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
            byte[] buffer = new byte[1024];
            int byteRead;
            while ((byteRead = fileInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
      * ************************************************************
      * @method  ShowToast
      * @description Toast提示框
      * @date: 2019/10/15 11:31
      * @author: wmf
      * ************************************************************
     */
    public void ShowToast(String msg) {
        Toast toast = Toast.makeText(MyApplication.getContext(), msg, Toast.LENGTH_SHORT);
        toast.setText(msg);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
    /**
      * ************************************************************
      * @method  ShowLoading
      * @description 加载等待框
      * @date: 2019/10/15 11:30
      * @author: wmf
      * ************************************************************
     */
    public void ShowLoading(String msg,Context context){  
        init(context);
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.dialog_loading, null);// 得到加载view
        LinearLayout layout = v.findViewById(R.id.dialog_loading_view);// 加载布局
        TextView tipTextView = v.findViewById(R.id.tipTextView);// 提示文字
        tipTextView.setText(msg);// 设置加载信息
        loadingDialog.setCancelable(false); // 是否可以按“返回键”消失
        loadingDialog.setCanceledOnTouchOutside(false); // 点击加载框以外的区域
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        /**
         *将显示Dialog的方法封装在这里面
         */
        Window window = loadingDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        loadingDialog.show();
    }
    // 关闭Loading
    public void HideLoading() {
        loadingDialog.dismiss();
    }

    //获取app信息
    public HashMap<String, Object> getInfo (Context context) {
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HashMap<String, Object> map = new HashMap<String, Object>();
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            map.put("name",context.getResources().getString(packageInfo.applicationInfo.labelRes));//应用名称
            map.put("code",packageInfo.versionCode);//版本号
            map.put("version",packageInfo.versionName);//版本名称
            map.put("package",packageInfo.packageName);//应用包名
            map.put("firstTime",time.format(new Date(packageInfo.firstInstallTime)));//第一次安装时间
            map.put("lastTime",time.format(new Date(packageInfo.lastUpdateTime)));//上次更新时间
            Log.e("zysoft",map.toString());
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return map;
    }
    public void installApk(String apkPath,Context context){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://"+apkPath),"application/vnd.android.package-archive");
        context.startActivity(intent);
    }
    /**
      * ************************************************************
      * @method  bitmapToBase64
      * @description bitmap转base64
      * @date: 2019/10/15 13:32
      * @author: wmf
      * @param {Bitmap bitmap} 图片bitmap
      * @return
      * ************************************************************
     */
    public String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                baos.flush();
                baos.close();
                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.getMessage();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.getMessage();
            }
        }
        return result;
    }
    //初始化数据库
    public void initDatabase(Context context){
        dbhelp = new MyDatabaseHelper(context);
        dbhelp.createDataBase();
    }
    public HashMap<String, Object> GetFile(HashMap<String,Object> imgList){
        HashMap<String, Object> img = new HashMap<String, Object>();
        for( Map.Entry<String, Object> key : imgList.entrySet()){
            img.put(key.getKey(),Base64File(key.getValue().toString(),Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+key.getKey()+".png"));
        }
        Log.e("zysoft_file",img.toString());
        return img;

    }
    //去除字符串换行
    public static String replaceBlank(String src) {
        String dest = "";
        if (src != null) {
            Pattern pattern = Pattern.compile("\t|\r|\n|\\s*");
            Matcher matcher = pattern.matcher(src);
            dest = matcher.replaceAll("");
        }
        Log.e("zysoft",dest);
        return dest;
    }
    public String Base64File(String base64,String url){
        byte[] buffer = Base64.decode(base64, Base64.DEFAULT);
        //转化为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(buffer);
        OutputStream Output = null;
        try {
            Output = new FileOutputStream(url);
            int length;
            while ((length = inputStream.read(buffer))>0){
                Output.write(buffer, 0, length);
                Output.flush();
                Output.close();
                inputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {//read
            e.printStackTrace();
        }
        return url;
    }
    //日期选择
    public void ShowDate(Context context, final EditText time,int i){
        Calendar c = Calendar.getInstance();
        int YEAR = c.get(Calendar.YEAR);
        int MONTH = c.get(Calendar.MONTH);
        int DAY_OF_MONTH = c.get(Calendar.DAY_OF_MONTH);
        switch (i){
            case 1:{
                YEAR = 2015;
                break;
            }
            case 2:{
                YEAR = 2025;
                break;
            }
            case 3:{
                YEAR = 1985;
                break;
            }
            case 4:{
                YEAR = c.get(Calendar.YEAR);
                break;
            }
        }
        DatePickerDialog  dialog = new DatePickerDialog(context,DatePickerDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // TODO Auto-generated method stub
                String month = "";
                String day = "";
                if(monthOfYear<10){
                    month = "0"+(monthOfYear+1);
                }else {
                    month = String.valueOf(monthOfYear+1);
                }
                if(dayOfMonth <10){
                    day = "0"+dayOfMonth;
                }else {
                    day = String.valueOf(dayOfMonth);
                }
                time.setText(year+"-"+month+"-"+day);
            }
        },YEAR,MONTH,DAY_OF_MONTH);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }
    public void  hideSoftInput(IBinder token,Context context) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
